package com.fzg.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.user.param.*;
import com.fzg.common.model.user.result.*;
import com.fzg.common.tool.MD5Tool;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.Enterprise;
import com.fzg.entity.JobInfor;
import com.fzg.entity.User;
import com.fzg.entity.UserJob;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.JobInforMapper;
import com.fzg.mapper.UserJobMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2021-12-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private JobInforMapper jobInforMapper;

    @Autowired
    private UserJobMapper userJobMapper;

    private final GridFsOperations gridFsOperations;

    public UserServiceImpl(GridFsOperations gridFsOperations) {
        this.gridFsOperations = gridFsOperations;
    }

    @Override
    public ResponseWrapper uploadFile(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            //上传文件返回文件ID
            ObjectId objectId = gridFsOperations.store(inputStream, file.getOriginalFilename(), file.getContentType());
            UploadResult result = new UploadResult();
            result.setEnclosureId(objectId.toString());
            return ResponseWrapper.markSuccess(result);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return ResponseWrapper.markCustomError("上传失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper editPassword(EditPasswordParam param) {
        // 通过账号查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user == null){
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            int update = enterpriseMapper.update(null, new LambdaUpdateWrapper<Enterprise>()
                    .set(Enterprise::getPassword, MD5Tool.getMD5(param.getNewPassword()))
                    .eq(Enterprise::getAid, enterprise.getAid()));
            if (update > 0){
                return ResponseWrapper.markCustomSuccess("修改成功！");
            }else {
                return ResponseWrapper.markCustomError("修改失败！");
            }
        }else {
            int update = userMapper.update(null, new LambdaUpdateWrapper<User>()
                    .set(User::getPassword, MD5Tool.getMD5(param.getNewPassword()))
                    .eq(User::getAid, user.getAid()));
            if (update > 0){
                return ResponseWrapper.markCustomSuccess("修改成功！");
            }else {
                return ResponseWrapper.markCustomError("修改失败！");
            }
        }
    }

    @Override
    public ResponseWrapper getUserList(GetUserListParam param) {

        // 返回结果
        GetUserListResult result = new GetUserListResult();

        Page<User> userPage = null;

        if (param.getAccount()!=null && param.getUserName()==null){
            // 账号不空，用户名为空
            userPage = userMapper.selectPage(
                    new Page<>(param.getPage(), param.getPageRow()),
                    new LambdaQueryWrapper<User>().ne(User::getAccountNumber, param.getAdminAccount())
                            .like(User::getAccountNumber, param.getAccount())
                            .orderByDesc(User::getCreateTime)
            );
        }
        if (param.getAccount() == null && param.getUserName() != null){
            // 账号空，用户名不空
            userPage = userMapper.selectPage(
                    new Page<>(param.getPage(), param.getPageRow()),
                    new LambdaQueryWrapper<User>().ne(User::getAccountNumber, param.getAdminAccount())
                            .like(User::getName, param.getUserName())
                            .orderByDesc(User::getCreateTime)
            );
        }
        if (param.getUserName() != null && param.getAccount() != null){
            // 账号和用户名都不为空
            userPage = userMapper.selectPage(
                    new Page<>(param.getPage(), param.getPageRow()),
                    new LambdaQueryWrapper<User>().ne(User::getAccountNumber, param.getAdminAccount())
                            .like(User::getAccountNumber, param.getAccount())
                            .like(User::getName,param.getUserName())
                            .orderByDesc(User::getCreateTime)
            );
        }
        // 总数
        if (userPage != null){
            // 总数
            result.setTotalNum((int)userPage.getTotal());

            // 用户列表
            ArrayList<GetUserListResultItem> userList = new ArrayList<>();

            // 查询出来的用户列表
            List<User> userListTemp = userPage.getRecords();
            for (User user : userListTemp) {
                GetUserListResultItem resultItem = new GetUserListResultItem();
                resultItem.setAid(user.getAid());
                resultItem.setDate(ToolForDateTime.LocalDateTimeToString(user.getCreateTime()));
                resultItem.setName(user.getName());
                resultItem.setAccount(user.getAccountNumber());
                resultItem.setAddress(user.getAddress());
                resultItem.setEmail(user.getEmail());
                resultItem.setPhone(user.getPhone());

                if (user.getGender().equals(1)){
                    resultItem.setGender("男");
                }else {
                    resultItem.setGender("女");
                }
                resultItem.setIdNumber(user.getIdentityNumber());
                if (user.getMaritalStatus().equals(0)){
                    resultItem.setMarital_status("未婚");
                }else {
                    resultItem.setMarital_status("已婚");
                }
                resultItem.setWorkExperience(user.getWorkExperience());
                if (user.getIsAdmin().equals(1)){
                    resultItem.setIsAdmin("是");
                }else {
                    resultItem.setIsAdmin("否");
                }
                resultItem.setAvatar(user.getAvatar());
                resultItem.setSchool(user.getSchool());
                userList.add(resultItem);
            }
            result.setUserList(userList);
            return ResponseWrapper.markSuccess(result);
        }else {
            return ResponseWrapper.markCustomError("查询失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delUser(Integer aid) {
        int deleteById = userMapper.deleteById(aid);
        if (deleteById > 0){
            return ResponseWrapper.markCustomSuccess("删除成功！");
        }else {
            return ResponseWrapper.markCustomError("删除失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper editUser(EditUserParam param) {
        int update = userMapper.update(null, new LambdaUpdateWrapper<User>().eq(User::getAid, param.getAid())
                .set(User::getName, param.getName())
                .set(User::getGender, param.getGender())
                .set(User::getPhone, param.getPhone())
                .set(User::getEmail, param.getEmail())
                .set(User::getAddress, param.getAddress())
                .set(User::getAvatar,param.getAvatar())
                .set(User::getIsAdmin,param.getIsAdmin().equals(true) ? 1 : 0)
                .set(User::getSchool,param.getSchool())
                .set(User::getMaritalStatus, param.getMaritalStatus()));
        if (update > 0){
            return ResponseWrapper.markCustomSuccess("编辑成功！");
        }else {
            return ResponseWrapper.markCustomError("编辑失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper addUser(AddUserParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().orderByDesc(User::getAid).last("limit 1"));
        Integer addUserAid = user.getAid() + 1;
        int insert = userMapper.insert(new User() {{
            setAid(addUserAid);
            setIsAdmin(0);
            setName(param.getName());
            setPassword(MD5Tool.getMD5("123456"));
            setAddress(param.getAddress());
            setEmail(param.getEmail());
            setGender(param.getGender());
            setPhone(param.getPhone());
            setMaritalStatus(param.getMaritalStatus());
            setIdentityNumber("未知");
            setAvatar(param.getAvatar());
            setIsAdmin(param.getIsAdmin().equals(true) ? 1 : 0);
            setSchool(param.getSchool());
            setAccountNumber(param.getAccount());
        }});
        if (insert > 0){
            return ResponseWrapper.markCustomSuccess("添加成功！");
        }else {
            return ResponseWrapper.markCustomError("添加失败！");
        }
    }

    @Override
    public ResponseWrapper checkAccount(CheckAccountParam param) {

        // 返回结果
        CheckAccouuntResult result = new CheckAccouuntResult();
        if (param.getAid().equals(-1) || param.getAid()==null){
            // 新增
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
            result.setIsExisted(user != null);
            return ResponseWrapper.markSuccess(result);
        }else {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .ne(User::getAid, param.getAid())
                    .eq(User::getAccountNumber, param.getAccount()));
            result.setIsExisted(user != null);
            return ResponseWrapper.markSuccess(result);
        }
    }

    @Override
    public ResponseWrapper checkPhone(CheckPhoneParam param) {
        // 返回结果
        CheckPhoneResult result = new CheckPhoneResult();
        if (param.getAid().equals(-1) || param.getAid()==null){
            // 新增
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, param.getPhone()));
            result.setIsExisted(user != null);
            return ResponseWrapper.markSuccess(result);
        }else {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .ne(User::getAid, param.getAid())
                    .eq(User::getPhone, param.getPhone()));
            result.setIsExisted(user != null);
            return ResponseWrapper.markSuccess(result);
        }
    }

    /**
     * 获取除了管理员以外的所有用户
     */
    @Override
    public ResponseWrapper getAllUserExceptAdmin() {
        ArrayList<User> result = new ArrayList<>();
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getIsAdmin, 0));
        if (userList.size() > 0){
            return ResponseWrapper.markSuccess(userList);
        }else {
            return ResponseWrapper.markSuccess(result);
        }
    }

    /**
     * 获取有求职信息的用户列表
     */
    @Override
    public ResponseWrapper getHaveHuntJobInfoUserAndJobList() {

        ArrayList<UserAndUserJobInfoResult> result = new ArrayList<>();

        // user  job_infor user_job
        List<UserJob> userJobs = userJobMapper.selectList(new LambdaQueryWrapper<UserJob>()
            .orderByDesc(UserJob::getCreateTime)
            .last("limit 20"));
        for (UserJob userJob : userJobs) {
            User user = userMapper.selectById(userJob.getUseraid());
            if (user != null){  // 该用户有需求的工作
                UserAndUserJobInfoResult resultChild = new UserAndUserJobInfoResult();
                resultChild.setUserAid(user.getAid());
                resultChild.setUserName(user.getName());
                resultChild.setUserAvatar(user.getAvatar());
                resultChild.setUserJobAid(userJob.getAid());
                resultChild.setJobInfoAid(userJob.getJobinfoaid());
                JobInfor jobInfor = jobInforMapper.selectById(userJob.getJobinfoaid());
                resultChild.setPositionName(jobInfor.getPositionName());
                result.add(resultChild);
            }
        }
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 将简历url保存到数据库
     *
     * @param param 参数
     */
    @Override
    public ResponseWrapper saveResumeUrl(SaveResumeUrl param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        user.setResumeUrl(param.getResumeUrl());
        int update = userMapper.updateById(user);
        if (update > 0){
            return ResponseWrapper.markSuccess();
        }else {
            return ResponseWrapper.markError();
        }
    }
}
